<script>
import axios from "axios";

export default {
  name: "CourseComponent",
  data() {
    return {

      uploadImageList: [],
      //图片上传
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,

      value1: '',
      input: '',
      dialogFormVisible: false,
      dialogTitle: '',//对话框标题
      form: {
        id:"",  //课程id
        courseName:"",  //课程名称
        tabularChart:"",  //列表图url,上传的图片
        coursetime:"",  //课程时长
        learnharvest:"", //学习收获
        readingquantity:"",  //阅读量
        typeId:"",
        teacherId:"",
        courseMount:"", //课件数量
        courseIntroduce:"", //课程简介
        applicablePopulation:"", //适用人群
        subscriptionNotice:"",   //订阅须知
        courseVideo:"",  //存储课程路径
        createTime: "",//创建时间
        updateTime:"",  //更新时间
        consultname:"",//咨询师名称，
        courseprice:"" //课程价格
      },
      tableData: [],
      tableData2: [],

      formLabelWidth: '120px',
      //查看关联门店里的搜索数据
      association: false,
      checkBtn2: {
        villageName2: "",
        pageNum: 1,
        pageSize: 10,
      },
      addAssociation: false,
      checkBtn3: {
        villageName3: "",
      },
      //搜索框数据对象
      searchContent: {
        courseName: "",
        time: [],
        pageNum: 1,
        pageSize: 7,
        type: "",
        consultName:""
      },
      xiaoquID: "",
      tableData3: [],
      row: {},      // 全局row 把scope.row赋给它
      allId: -1,   //全局id用来在新增和修改是做判断
      page: {
        pageSize: 10,    //默认每页显示10条
        currentPage: 1,  //默认显示第一页
        total: 0 //总条数
      },
      //所有类型
      allType:[],
      //所有咨询师
      allTeacher:[]

    }
  },
  //   页面初始化后执行
  created() {

    this.flushPage();
    this.queryAllType();
    this.queryAllTeacher();

  },
  methods: {

    //获取所有课程类型
    queryAllType(){
      this.axios.get("course/queryAllType").then((res) => {
        // console.log("~~~~~~~~~~~所有类型~~~~~~~~~~~~~~~~~~")
        // console.log(res.data)
        this.allType = res.data.data;

      }).catch(err => {
        console.log(err);
      })
    },
    //获取所有咨询师
    queryAllTeacher(){
      this.axios.get("course/queryAllTeacher").then((res) => {
        // console.log("~~~~~~~~~~~所有咨询师~~~~~~~~~~~~~~~~~~")
        // console.log(res.data)
        this.allTeacher = res.data.data;

      }).catch(err => {
        console.log(err);
      })
    },
    handleRemove(file) {
      this.uploadImageList = this.uploadImageList.filter(item => item.name !== file.name);
      if (this.uploadImageList.length === 0) {
        this.form.tabularChart = '';
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },

    uploadImg(r,file,fileList){
      console.log(r.data);
      if(r.code===200){
        this.form.tabularChart=r.data
        this.uploadImageList=fileList
      } else {
        this.$message.error('上传失败');
      }
    },
    //添加以及修改
    save() {
      if (this.allId === -1) {   // 新增
        this.dialogFormVisible = false;

        this.axios.post("course/addCourse", {
          id:this.form.id,
          coursename:this.form.courseName,
          tabularchart:this.form.tabularChart,
          coursetime:this.form.coursetime,
          learnharvest:this.form.learnharvest,
          readingquantity:this.form.readingquantity,
          typeId:this.form.typeId,
          teacherId:this.form.teacherId,
          coursemount:this.form.courseMount,
          courseintroduce:this.form.courseIntroduce,
          applicablepopulation:this.form.applicablePopulation,
          subscriptionnotice:this.form.subscriptionNotice,
          coursevideo:this.form.courseVideo,
          // createtime: this.formatDateTime(new Date()),
          // updatetime:this.formatDateTime(new Date())
        }).then((res) => {
           console.log("-------------------添加课程------------------")
           console.log(res.data);
          if(res.data.code==200){
            this.$message.success("添加成功")
          }
          this.clearForm();
          this.flushPage();
        })
      } else {      //allId不为空 修改
        this.dialogFormVisible = false;

        this.axios.put("/course/updateCourse", null,{
          params:{
            id:this.form.id,
            coursename:this.form.courseName,
            tabularchart:this.form.tabularChart,
            coursetime:this.form.coursetime,
            learnharvest:this.form.learnharvest,
            readingquantity:this.form.readingquantity,
            typeId:this.form.typeId,
            teacherId:this.form.teacherId,
            coursemount:this.form.courseMount,
            courseintroduce:this.form.courseIntroduce,
            courseprice:this.form.courseprice,
            applicablepopulation:this.form.applicablePopulation,
            subscriptionnotice:this.form.subscriptionNotice,
            coursevideo:this.form.courseVideo,
            // createtime: "",
            updatetime:this.formatDateTime(new Date())
          }
        }).then((res) => {
          console.log(res.data);
          if(res.data.code==200){
            this.$message.success("修改成功")
          }
          // this.clearForm();
          setTimeout(this.flushPage, 500)
        })
      }
    },
    //新增小区
    addXiaoqu() {
      this.dialogTitle = "新增课程";
      this.dialogFormVisible = true;
      this.allId = -1; //为-1时新增
      this.clearForm()
    },
    //保存后清空表单
    clearForm() {
          this.form.id=""; //课程id
          this.form.courseName="";  //课程名称
          // this.form.tabularChart=""; //列表图url,上传的图片
          this.form.coursetime=""; //课程时长
          this.form.learnharvest=""; //学习收获
          this.form.readingquantity="";  //阅读量
          this.form.typeId="";
          this.form.teacherId="";
          this.form.courseMount=""; //课件数量
          this.form.courseIntroduce=""; //课程简介
          this.form.applicablePopulation=""; //适用人群
          this.form.subscriptionNotice="";   //订阅须知
          this.form.courseVideo=""; //存储课程路径
          this.form.createTime= "";//创建时间
          this.form.updateTime="" //更新时间
          this.form.courseprice="";
          this.uploadImageList = [];
    },
    //格式化时间
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //取消
    cancel() {
      this.dialogFormVisible = false;
    },
    //编辑课程
    editClick(row) {
      this.dialogTitle = "编辑课程";
      this.dialogFormVisible = true;
      this.row = row;
      this.allId = this.row.id;
      console.log(this.allId);
      console.log("===============打印row===========")
      console.log(this.row)

      // 图片回显
      if (row.tabularchart) {
        this.uploadImageList = [{
          name: row.tabularchart,
          url: `http://localhost:8080/course/down?filename=${row.tabularchart}`
        }];
      } else {
        this.uploadImageList = [];
      }
      this.form.id=this.row.id;
      this.form.courseVideo=row.coursevideo;
      this.form.typeId=this.row.typeId;
      this.form.teacherId=this.row.teacherId;
      this.form.applicablePopulation=this.row.applicablepopulation;
      this.form.courseMount=this.row.coursemount;
      this.form.subscriptionNotice=row.subscriptionnotice;
      this.form.courseName=this.row.coursename;
      this.form.tabularChart=this.row.tabularchart;
      this.form.consultname=this.row.consultName
      this.form.updateTime=row.updatetime;
      this.form.createTime=row.createtime;
      this.form.courseIntroduce=row.courseintroduce
      this.form.coursetime=row.coursetime
      this.form.courseprice=row.courseprice

    },


    //刷新页面
    flushPage() {
      this.axios.get("course/queryAll",{
        params:{
          pageNum:this.page.currentPage,
          pageSize:this.page.pageSize
        }
      }).then((res) => {
        console.log("~~~~~~~~~~~~~~列表数据res.data~~~~~~~~~~~~~~~~~~~")
        console.log(res.data)
        this.tableData = res.data.data.list;
        //页面加载时添加总数量
        this.page.total = res.data.data.total;

      }).catch(err => {
        console.log(err);
      })
    },
    //删除小区
    deleteClick(index) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.delete("/course/deleteCourse", {
          params:{
            id: index
          }
        }).then((res) => {
          if(res.data.data>0){
            this.$message.success("删除成 功!")
          }else {
            this.$message.error("删除失败")
          }

          this.flushPage();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //搜索  查询的数据给了表格
    searchClick() {
      this.axios.get('/course/queryAllLike',
          {
            params: {
              //传输的参数
              courseName: this.searchContent.courseName,
              type: this.searchContent.type,
              consultName:  this.searchContent.consultName,
              createtime: this.searchContent.time[0] === undefined ? '' : this.formatDateTime(this.searchContent.time[0]),
              updatetime: this.searchContent.time[1] === undefined ? '' : this.formatDateTime(this.searchContent.time[1]),
              pageNum:this.page.currentPage,
              pageSize:this.page.pageSize
            }
          }
      ).then((res) => {
        console.log("~~~~~~~~~~~~~~~搜索打印res.data~~~~~~~~~~~~~~~~~~~~~~~")
        console.log(res.data)
        this.tableData = res.data.data.list;
        // console.log("------------")
        // console.log(this.tableData)
        //页面加载时添加总数量
        this.page.total = res.data.data.total;

      }).catch(err => {
      })
    },
    //分页函数
    //点击按钮切换页面
    handleCurrentChange(currentPage) {
      this.page.currentPage = currentPage; //每次点击分页按钮，当前页发生变化
      console.log("页码切换：" + this.page.currentPage);          // 获取改变页码后的数据
      this.flushPage();
    },
  }
}
</script>

<template>
  <div class="xiaoqu">
    <div class="xiaoqu-content">
      <div class="searchBox">
        <div class="searchLi">
          <span class="xiaoquName">课程名称：</span>
          <input type="text" autocomplete="off" v-model="searchContent.courseName">
        </div>
        <div class="searchLi">
          <span class="xiaoquName">课程分类：</span>
          <input type="text" autocomplete="off" v-model="searchContent.type">
        </div>
        <div class="searchLi">
          <span class="xiaoquName">咨询师名称：</span>
          <input type="text" autocomplete="off" v-model="searchContent.consultName" >
        </div>
        <div class="searchLi">
          <span>创建时间：</span>
          <el-date-picker
              v-model="searchContent.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </div>
        <div class="searchBtn">
          <el-button type="primary" @click="searchClick">搜索</el-button>
        </div>
      </div>
      <div class="addXiaoquBtn">
        <el-button type="text" @click="addXiaoqu" class="addBtn">新增课程</el-button>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="课程名称" :label-width="formLabelWidth">
              <el-input v-model="form.courseName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="课程图片" :label-width="formLabelWidth">
              <el-upload
                  v-if="dialogFormVisible"
                  action="http://localhost:8080/course/upload"
                  list-type="picture-card"
                  :auto-upload="true"
                  :on-success="uploadImg"
                  :file-list="uploadImageList"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
        <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>

            <el-form-item label="课程时长" :label-width="formLabelWidth">
              <el-input v-model="form.coursetime" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="课件数量" :label-width="formLabelWidth">
              <el-input v-model="form.courseMount" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="课程简介" :label-width="formLabelWidth">
              <el-input v-model="form.courseIntroduce" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="课程价格" :label-width="formLabelWidth">
              <el-input v-model="form.courseprice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="适用人群" :label-width="formLabelWidth">
              <el-input v-model="form.applicablePopulation" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="课程分类" :label-width="formLabelWidth">
              <el-select v-model="form.typeId" placeholder="请选择">
                <el-option
                    v-for="item in allType"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="订阅需知" :label-width="formLabelWidth">
              <el-input v-model="form.subscriptionNotice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="咨询师" :label-width="formLabelWidth">
              <el-select v-model="form.teacherId" placeholder="请选择">
                <el-option
                    v-for="item in allTeacher"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程视频url" :label-width="formLabelWidth">
              <el-input v-model="form.courseVideo" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button @click="save">保 存</el-button>
          </div>
        </el-dialog>
      </div>
      <div class="xiaoqu-table">
        <el-table
            :data="tableData"
            border
            :cell-style="{'text-align':'center'}"
            :header-cell-style="{background: '#1890ff',color: '#ffffff','text-align': 'center'}">
          <el-table-column
              prop="id"
              label="Id">
          </el-table-column>
          <el-table-column
              prop="coursename"
              label="课程名称">
          </el-table-column>

          <el-table-column
              label="图片">
            <template slot-scope="scope">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="'http://localhost:8080/course/down?filename='+scope.row.tabularchart"
                  fit="fill"></el-image>
            </template>
          </el-table-column>
          <el-table-column
              prop="courseintroduce"
              label="课程简介">
          </el-table-column>
          <el-table-column
              prop="applicablepopulation"
              label="适用人群">
          </el-table-column>

          <el-table-column
              prop="courseType"
              label="课程分类">
          </el-table-column>
          <el-table-column
              prop="consultName"
              label="咨询师名称">
          </el-table-column>
          <el-table-column
              prop="subscriptionnotice"
              label="订阅需知">
          </el-table-column>
          <el-table-column
              prop="createtime"
              label="创建时间">
          </el-table-column>
          <el-table-column
              prop="coursevideo"
              label="课程视频url">
          </el-table-column>
          <el-table-column
              label="操作">
            <template slot-scope="scope">
              <el-button  type="text" size="small">查看关联门店</el-button>
              <!--   弹窗内容-->
              <el-dialog
                  title="查看关联门店"
                  :visible.sync="association"
                  :close-on-click-modal="false"
              >
                <el-form :model="checkBtn2">
                  <el-form-item>
                    <el-input
                        v-model="checkBtn2.villageName2"
                        autocomplete="off"
                        :style="{
                                            width: '200px',
                                            marginRight: '20px',
                                            float: 'left',
                                          }"></el-input>
                    <el-form-item style="margin-left: 10px; float: left">
                      <el-button type="primary" >搜索</el-button>
                      <el-button type="primary">添加关联门店</el-button>
                      <!--  addAssociation = true  -->
                      <el-dialog
                          title="添加关联门店"
                          :visible.sync="addAssociation"
                          append-to-body>
                        <el-form :model="checkBtn3">
                          <el-form-item>
                            <el-input
                                v-model="checkBtn3.villageName3"
                                autocomplete="off"
                                :style="{
                                        width: '200px',
                                        marginRight: '20px',
                                        float: 'left',
                                        }"></el-input>
                            <el-form-item
                                style="margin-left: 10px; float: left">
                              <el-button type="primary" @click="lookAssociation"
                              >搜索
                              </el-button>
                            </el-form-item>
                            <el-form-item>
                              <el-table
                                  :data="tableData3"
                                  border
                                  style="width: 100%"
                                  :header-cell-style="{
                                   backgroundColor: '#1890FF',
                                   color: '#FFFFFF',
                                    textAlign: 'center',
                                    }">
                                <el-table-column
                                    prop="panghuShopId"
                                    label="序号"
                                    width="50"
                                ></el-table-column>
                                <el-table-column
                                    prop="shopName"
                                    label="名称"
                                ></el-table-column>
                                <el-table-column
                                    prop="panghuShopId"
                                    label="ID"
                                ></el-table-column>
                                <el-table-column prop="shopSort" label="排序"></el-table-column>
                                <el-table-column
                                    prop="shopAddress"
                                    label="地址"
                                ></el-table-column>
                                <el-table-column
                                    prop="salesVolume"
                                    label="订单数量"
                                ></el-table-column>
                              </el-table>
                            </el-form-item>
                          </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                          <el-button @click="addAssociation = false">取 消</el-button>
                          <el-button type="primary" @click="addAssociation = false">确 定</el-button>
                        </div>
                      </el-dialog>
                    </el-form-item>
                  </el-form-item>
                  <el-table
                      :data="tableData2"
                      border
                      style="width: 100%"
                      :header-cell-style="{
                                          backgroundColor: '#1890FF',
                                          color: '#FFFFFF',
                                          textAlign: 'center',
                                        }">
                    <el-table-column
                        prop="panghuShopId"
                        label="序号"
                        width="50"
                    ></el-table-column>
                    <el-table-column
                        prop="shopName"
                        label="名称"
                    ></el-table-column>
                    <el-table-column
                        prop="panghuShopId"
                        label="ID"
                    ></el-table-column>
                    <el-table-column prop="shopSort" label="排序"></el-table-column>
                    <el-table-column
                        prop="shopAddress"
                        label="地址"
                    ></el-table-column>
                    <el-table-column
                        prop="salesVolume"
                        label="订单数量"
                    ></el-table-column>
                    <el-table-column label="操作" width="100"></el-table-column>
                  </el-table>
                </el-form>
                <!-- 分页-->

                <div slot="footer" class="dialog-footer">
                  <el-button @click="association = false">取 消</el-button>
                </div>
              </el-dialog>

              <el-button @click="editClick(scope.row)" type="text" size="small">编辑小区</el-button>
              <el-button @click="deleteClick(scope.row.id)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页按钮-->
      <div class="block">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="page.pageNum"
            :page-size="10"
            layout="prev, pager, next,jumper, ->, total"
            :total="page.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<style scoped>
.xiaoqu {
  height: 800px;
  /*background-color: hotpink;*/
}

.xiaoqu-content {
  padding: 20px;
}

.searchBox {
  display: flex;
  justify-content: flex-start;
}

.searchLi {
  margin-right: 20px;
}

.addXiaoquBtn {
  margin-top: 20px;
}

input {
  height: 34px;
  outline: none;
  border: 1px solid #aaa;
  padding: 0 15px;
  border-radius: 5px;
}

input:hover {
  border: 1px solid #555555;
}

input:focus {
  border: 1px solid #409eff;
}

.addBtn {
  padding: 10px 20px;
  background-color: #409eff;
  color: whitesmoke;
  border: 1px solid #409eff;
}

.xiaoqu-table {
  margin-top: 20px;
  table-layout: auto;
}
</style>